In [ ]:
%%HTML
<style>
.container { width:100% }
</style>

Utilities

The global variable Cache is used as a cache for the function valuedefined later.


In [ ]:
Cache = {}

The function memoize takes a function f as its argument. It returns a memoized version of the function f. This memoized version will store all results in the Cache and look them up instead of recomputing them.


In [ ]:
def memoize(f):
    global Cache
    
    def f_memoized(*args):
        if args in Cache:
            return Cache[args]
        result = f(*args)
        Cache[args] = result
        return result
    
    return f_memoized

The Minimax Algorithm

In order to have some variation in our game, we use random numbers to choose between optimal moves.


In [ ]:
import random
random.seed(1)

Given a player p, the function other(p) computes the opponent of p. This assumes that there are only two players and the set of all players is stored in the global variable Players.


In [ ]:
other = lambda p: [o for o in Players if o != p][0]

The function value takes two arguments:

  • State is the current state of the game,
  • player is a player.

The function value returns the value that the given State has for player if both players play optimal game. This values is an element from the set $\{-1, 0, 1\}$.

  • If player can force a win, the return value is 1.
  • If player can at best force a draw, the return value is 0.
  • If player might loose even when playing optimal, the return value is -1.

For reasons of efficiency, this function is memoized.


In [ ]:
@memoize
def value(State, player):
    if finished(State):
        return utility(State, player)
    return max([ -value(ns, other(player)) for ns in next_states(State, player) ])

The function best_move takes two arguments:

  • State is the current state of the game,
  • player is a player.

The function best_move returns a pair of the form $(v, s)$ where $s$ is a state and $v$ is the value of this state. The state $s$ is a state that is reached from State if player makes one of her optimal moves. In order to have some variation in the game, the function randomly chooses any of the optimal moves.


In [ ]:
def best_move(State, player):
    NS        = next_states(State, player)
    bestVal   = value(State, player)
    BestMoves = [s for s in NS if -value(s, other(player)) == bestVal]
    BestState = random.choice(BestMoves)
    return bestVal, BestState

The next line is needed because we need the function IPython.display.clear_output to clear the output in a cell.


In [ ]:
import IPython.display

The function play_game plays on the given canvas. The game played is specified indirectly by specifying the following:

  • Start is a global variable defining the start state of the game.
  • next_states is a function such that $\texttt{next_states}(s, p)$ computes the set of all possible states that can be reached from state $s$ if player $p$ is next to move.
  • finished is a function such that $\texttt{finished}(s)$ is true for a state $s$ if the game is over in state $s$.
  • utility is a function such that $\texttt{utility}(s, p)$ returns either -1, 0, or 1 in the terminal state $s$. We have that
    • $\texttt{utility}(s, p)= -1$ iff the game is lost for player $p$ in state $s$,
    • $\texttt{utility}(s, p)= 0$ iff the game is drawn, and
    • $\texttt{utility}(s, p)= 1$ iff the game is won for player $p$ in state $s$.

In [ ]:
def play_game(canvas):
    State = Start
    while (True):
        firstPlayer = Players[0]
        val, State  = best_move(State, firstPlayer);
        draw(State, canvas, f'For me, the game has the value {val}.')
        if finished(State):
            final_msg(State)
            break
        IPython.display.clear_output(wait=True)
        State = get_move(State)
        draw(State, canvas, '')
        if finished(State):
            IPython.display.clear_output(wait=True)
            final_msg(State)
            break

In [ ]:
%run Tic-Tac-Toe.ipynb

With memoization, computing the value of the start state takes 95 ms. Without memoization, it takes 5 seconds.


In [ ]:
%%time
val = value(Start, 'X')

In [ ]:
val

We check how many different states are stored in the Cache.


In [ ]:
len(Cache)

Let's draw the board.


In [ ]:
canvas = create_canvas(Start)
draw(Start, canvas, f'Current value of game for "X": {val}')

Now its time to play. In the input window that will pop up later, enter your move in the format "row,col" with no space between row and column.


In [ ]:
play_game(canvas)

In [ ]: